package com.atguigu;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemon3 {

	public static void main(String[] args) {
		
		final Relay2 re = new Relay2();
		final Lock l = new ReentrantLock();
		final Condition con1 = l.newCondition();
		final Condition con2 = l.newCondition();
		final Condition con3 = l.newCondition();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					re.printA();
				}
			}
		}, "AA").start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					re.printB();
				}
			}
		}, "BB").start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < 10; i++) {
					re.printC();
				}
			}
			}, "CC").start();

	}
}


class Relay2{
	
	private int num = 1;
	private Lock l = new ReentrantLock();
	private Condition con1 = l.newCondition();
	private Condition con2 = l.newCondition();
	private Condition con3 = l.newCondition();
	
	public void printA(){
		l.lock();try {
			while(num != 1){
				con1.await();
			}
			System.out.println("AAAAAAAA");
			num = 2;
			con2.signal();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			l.unlock();
		}
		
	}
	
	public void printB(){
		l.lock();
		try {
			while(num != 2){
				con2.await();
			}
			System.out.println("BBBBBBBB");
			num = 3;
			con3.signal();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			l.unlock();
		}
		
		
	}
	
	public void printC(){
		l.lock();
		try {
			while(num != 3){
				con3.await();
			}
			System.out.println("CCCCCCCC");
			num = 1;
			con1.signal();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			l.unlock();
		}
		
	}
	
}